package com.d6game.web.controller;

import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import weibo4j.Comments;
import weibo4j.Friendships;
import weibo4j.Timeline;
import weibo4j.examples.oauth2.Log;
import weibo4j.http.AccessToken;
import weibo4j.model.Comment;
import weibo4j.model.CommentWapper;
import weibo4j.model.Paging;
import weibo4j.model.Status;
import weibo4j.model.User;
import weibo4j.model.UserWapper;
import weibo4j.model.WeiboException;

import com.d6game.web.annotation.LoginRequired;
import com.d6game.web.entity.Message;
import com.d6game.web.util.ConfigManager;
import com.d6game.web.util.DateJsonValueProcessor;
import com.d6game.web.util.MD5;
import com.d6game.web.util.ResponseUtil;

@Controller
@RequestMapping(value = "/api")
public class APIController extends BaseController {
	private static Logger logger = LoggerFactory.getLogger(CommonController.class);  


	/**
	 * 生成激活码
	 * @param request
	 * @param response
	 * @param session
	 */
	@RequestMapping(value="/generate_code")
	public void generate_code(HttpServletRequest request, HttpServletResponse response, HttpSession session){
		String machine_id = request.getParameter("machine_id");
		Integer hash = Math.abs(MD5.encrypt(machine_id+ConfigManager.getInstance().getConfig("secret")).hashCode());
		logger.debug("generate_code,the machine_id is "+machine_id+" and the activation code is "+hash.hashCode());
		ResponseUtil.sendStringResponse(response, hash.toString()); 
	}
	/**
	 * 获取我的关注
	 * @param request
	 * @param response
	 * @param session
	 */
	@RequestMapping(value="/my_follow")
	public void my_follow(HttpServletRequest request, HttpServletResponse response, HttpSession session){
		User user  = (User) session.getAttribute("wb_user");
		String uid = user.getId();
		AccessToken accessToken = (AccessToken) session.getAttribute("accessToken");
		String access_token = accessToken.getAccessToken();
		Friendships fm = new Friendships();
		fm.client.setToken(access_token);
		UserWapper users = null;
		try {
			users = fm.getFriendsByID(uid);
		} catch (WeiboException e) {
			e.printStackTrace();
		}
		JsonConfig jsonConfig = new JsonConfig();
		jsonConfig.registerJsonValueProcessor(Date.class,new DateJsonValueProcessor("yyyy-MM-dd HH:mm:ss")); 
		JSONArray jsonResult = JSONArray.fromObject(users,jsonConfig);
		ResponseUtil.sendStringResponse(response, jsonResult); 
	}
	/**
	 * 添加评论
	 * @param request
	 * @param response
	 * @param session
	 */
	@RequestMapping(value="/create_comment")
	public void create_comment(HttpServletRequest request, HttpServletResponse response, HttpSession session){
		Message message = new Message(1,"");
		AccessToken accessToken = (AccessToken) session.getAttribute("accessToken");
		String access_token = accessToken.getAccessToken();
		String comments = request.getParameter("comment");
		String fullComments = comments;
		String id = request.getParameter("id");
		String atUser = request.getParameter("at_user");
		String[] atUserArray = atUser.split(",");
		Comments cm = new Comments();
		cm.client.setToken(access_token);
		if(atUserArray.length > 0){
			fullComments += " @"+atUserArray[0];
		} 
		if(atUserArray.length == 1){
			try {
				Comment comment = cm.createComment(fullComments, id);
				fullComments = comments;
				Log.logInfo(comment.toString());
			} catch (WeiboException e) {
				logger.error(e.getMessage());
				message.setCode(2);
				message.setMessage("评论微博API异常");
			}
		}else {
			for (int i = 1; i < atUserArray.length; i++) {
				if((fullComments+" @"+atUserArray[i]).length() > 140 || i == (atUserArray.length-1)){
					try {
						Comment comment = cm.createComment(fullComments, id);
						fullComments = comments;
						Log.logInfo(comment.toString());
					} catch (WeiboException e) {
						logger.error(e.getMessage());
						message.setCode(2);
						message.setMessage("评论微博API异常");
					}
				}else {
					fullComments += " @"+atUserArray[i];
				}
			}
		}
		try {
			CommentWapper cw = cm.getCommentById(id, new Paging(1, 50), 0);
			//JsonConfig jsonConfig = new JsonConfig();
			//jsonConfig.registerJsonValueProcessor(Date.class,new DateJsonValueProcessor("yyyy-MM-dd HH:mm:ss")); 
			//JSONArray jsonResult = JSONArray.fromObject(cw,jsonConfig);
			message.setCode(1);
			message.setData(Long.valueOf(cw.getTotalNumber()).toString());
		} catch (WeiboException e) {
			logger.error(e.getMessage());
			message.setCode(2);
			message.setMessage("获取评论列表API异常");
		}
		JSONObject json = JSONObject.fromObject(message);
		ResponseUtil.sendStringResponse(response, json); 
	}
	/**
	 * 发布一条微博
	 * @param request
	 * @param response
	 * @param session
	 * @param model
	 */
	@LoginRequired
	@RequestMapping(value="/update_status")
	public void update_status(HttpServletRequest request, HttpServletResponse response, HttpSession session, Model model){
		AccessToken accessToken = (AccessToken) session.getAttribute("accessToken");
		String access_token = accessToken.getAccessToken();
		String statuses = request.getParameter("statuses");
		Timeline tm = new Timeline();
		tm.client.setToken(access_token);
		try {
			Status status = tm.UpdateStatus(statuses);
			JsonConfig jsonConfig = new JsonConfig();
			jsonConfig.registerJsonValueProcessor(Date.class,new DateJsonValueProcessor("yyyy-MM-dd HH:mm:ss")); 
			JSONObject json = JSONObject.fromObject(status,jsonConfig);
			ResponseUtil.sendStringResponse(response, json); 
		} catch (WeiboException e) {
			logger.error(e.getMessage());
		}	
	}
}
